#include <fcntl.h> /* For O_* constants */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <unistd.h>
#include <thread>
#include <chrono>

#define SHM_NAME "/shm"

int main(void) {
    int ret = 0;

    ///< 创建和读端相同的文件标识
    int shm_fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, 0666);
    if (shm_fd == -1) {
        printf("shm_open error\n");
    }

    ///< 设置共享内存文件为8KB
    ftruncate(shm_fd, 8 * 1024);

    ///< 获取共享内存文件相关属性信息
    struct stat filestat = {0};
    fstat(shm_fd, &filestat);
    printf("st_size = %ld\n", filestat.st_size);

    ///< 内存映射
    char *shm_ptr = (char *)mmap(NULL, filestat.st_size, PROT_READ | PROT_WRITE,
                                 MAP_SHARED, shm_fd, 0);

    ///< 向共享内存中写入数据
    while (true)
    {
        char buf[] = "Hello Randy, go to sleep, now!";
        memmove(shm_ptr, buf, sizeof(buf));

        using namespace std::chrono_literals;
        std::this_thread::sleep_for(2000ms);
    }

    return 0;
}